package com.huluobo.day11_im.weight;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AlphaAnimation;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class MyView extends View {
    private Paint paint;

    private int progress;

    private String timeString;

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    private void initPaint() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(5);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setTextSize(100);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        RectF rectF = new RectF(10, 10, 510, 510);
        canvas.drawArc(rectF, 270, progress, false, paint);
        canvas.drawText(timeString, 230, 280, paint);
    }

    public void start(int time) {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, 360);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(@NonNull ValueAnimator animation) {
                progress = (int) valueAnimator.getAnimatedValue();
                invalidate();
            }
        });
        valueAnimator.setDuration(time * 1000);
        valueAnimator.start();

        ValueAnimator valueAnimatorText = ValueAnimator.ofInt(time, 0);
        valueAnimatorText.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(@NonNull ValueAnimator animation) {
                timeString = String.valueOf(valueAnimatorText.getAnimatedValue());
                invalidate();
            }
        });
        valueAnimatorText.setDuration(time * 1000);
        valueAnimatorText.start();
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                onAnimEndListener.onAnimEnd();
            }
        });
    }

    public interface OnAnimEndListener {
        void onAnimEnd();
    }

    OnAnimEndListener onAnimEndListener;

    public void setOnAnimEndListener(OnAnimEndListener onAnimEndListener) {
        this.onAnimEndListener = onAnimEndListener;
    }
}
